package cn.wolfcode.p2p.website.controller;


import cn.wolfcode.p2p.base.domain.RealAuth;
import cn.wolfcode.p2p.base.domain.UserInfo;
import cn.wolfcode.p2p.base.exception.DisplayableException;
import cn.wolfcode.p2p.base.service.IRealAuthService;
import cn.wolfcode.p2p.base.service.IUserInfoService;
import cn.wolfcode.p2p.base.util.JSONResult;
import cn.wolfcode.p2p.util.RequireLogin;
import cn.wolfcode.p2p.util.UploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class RealAuthController {

    @Autowired
    private IUserInfoService userInfoService;
    @Autowired
    private IRealAuthService realAuthService;
    @Value("${file.path}")
    private String filePath;

    @RequestMapping("/realAuth")
    @RequireLogin
    public String realAuthPage(Model model){
        UserInfo current = userInfoService.getCurrent();
        if (current.getHasRealAuth()) {
            model.addAttribute("auditing", false);
            model.addAttribute("realAuth", realAuthService.get(current.getRealAuthId()));
            return "realAuth_result";
        } else {
            if (current.getRealAuthId() == null) { //没有审核或审核不通过,跳转到未审核界面
                return "realAuth";
            } else { //待审核界面
                model.addAttribute("auditing", true);
                return "realAuth_result";
            }
        }
    }


    @RequestMapping("/realAuth_save")
    @ResponseBody
    public JSONResult realAuthApply(RealAuth realAuth){
        JSONResult result = null;
        try {
            realAuthService.realAuthApply(realAuth);
            result = new JSONResult("");
        } catch (DisplayableException ex) {
            //异常需要在前台显示
            ex.printStackTrace();
            result = new JSONResult(false, ex.getMessage());
        } catch (Exception e){
            //异常记录到数据库或日志文件中
            e.printStackTrace();
            result = new JSONResult(false, "系统异常,请联系管理员");
        }
        return result;
    }

    @ResponseBody
    @RequestMapping("/uploadImg")
    public String uploadImg(MultipartFile img){
        String path = UploadUtil.upload(img, filePath);
        return path;
    }
}
